package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.common.config.YmlConfig;
import com.yt.sys.models.bo.AssignPermissionsSaveBO;
import com.yt.sys.models.bo.SysRoleSaveBO;
import com.yt.sys.models.dto.SysPermissionsDTO;
import com.yt.sys.models.dto.SysRolePermissionDTO;
import com.yt.sys.models.dto.UserRoleRelationDTO;
import com.yt.sys.models.service.ISysPermissionsService;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.service.IUserRoleRelationService;
import com.yt.sys.models.vo.RolePermissionDetailVO;
import com.yt.sys.models.vo.SysRolePermissionVO;
import com.yt.sys.models.vo.SysRoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.bo.SysRoleBO;
import com.yt.sys.models.dto.SysRoleDTO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色详情控制器
 *
 * @author thekai
 * @Date 2025-10-23 11:32:40
 */

@RestController
@RequestMapping("/api/sysRole")
@Slf4j
@Api(value = "SysRoleApiController",tags = "角色详情Api接口")
public class SysRoleApiController {

    @DubboReference
    private ISysRoleService sysRoleService;
    @DubboReference
    private IUserRoleRelationService userRoleRelationService;
    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;
    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private ISysPermissionsService sysPermissionsService;


    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysRoleDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        SysRoleDTO dto = sysRoleService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "角色详情列表",notes = "角色详情列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysRoleDTO>> queryPageList(SysRoleBO bo){
        Wrapper<SysRoleDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null){
            wrapper.eq("status", bo.getStatus());
        }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<SysRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysRoleService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    @ApiOperation(value = "添加角色详情",notes = "添加角色详情")
    @PostMapping(value = "/insert")
    public Result insert(@RequestBody SysRoleSaveBO saveBO) {
        boolean flag = sysRoleService.add(saveBO);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }
    @PostMapping("/sysRoleDelete")
    @ApiOperation(value = "角色删除", notes = "角色删除")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> sysRoleDelete(@RequestParam Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        //1.删除角色表
        boolean flag = sysRoleService.deleteById(id);
        //2.删除用户角色关系表
        Wrapper<UserRoleRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", id);
        userRoleRelationService.delete(wrapper);
        //3.删除角色权限关系表
        Wrapper<SysRolePermissionDTO> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("role_id", id);
        List<SysRolePermissionDTO> sysRolePermissionDTOList = sysRolePermissionService.selectList(wrapper1);
        if (sysRolePermissionDTOList != null && sysRolePermissionDTOList.size() > 0){
            sysRolePermissionService.delete(wrapper1);
        }

        return new Result<>(flag);
    }


    @PostMapping("/queryRole")
    @ApiOperation(value = "查询角色信息", notes = "查询角色信息")
    public Result<List<SysRoleVO>> queryRole() {
        List<SysRoleVO> sysRoleVOS = sysRoleService.query();
        return new Result<>(sysRoleVOS);
    }
    @PostMapping("/updateSysRole")
    @ApiOperation(value = "角色编辑", notes = "角色编辑")
    public Result<Boolean> updateSysRole(@RequestBody SysRoleSaveBO saveBO) {
        SysRoleDTO sysRoleDTO = new SysRoleDTO();
        if (saveBO == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        BeanUtils.copyProperties(saveBO, sysRoleDTO);
        boolean flag = sysRoleService.updateById(sysRoleDTO);
        return new Result<>(flag);
    }

    @PostMapping("/assignPermissions")
    @ApiOperation(value = "权 限分配", notes = "权限分配")
    @Transactional
    public Result assignPermissions(@RequestBody AssignPermissionsSaveBO saveBO) {
        if (saveBO == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", saveBO.getRoleId());
        sysRolePermissionService.delete(wrapper);
        List<Long> permissIdList = saveBO.getPermIds();
        for (Long permissId : permissIdList) {
            SysRolePermissionDTO sysRolePermissionDTO = new SysRolePermissionDTO();
            sysRolePermissionDTO.setId(ymlConfig.getPkId());
            sysRolePermissionDTO.setRoleId(saveBO.getRoleId());
            sysRolePermissionDTO.setPermissionId(permissId);
            sysRolePermissionService.insert(sysRolePermissionDTO);
        }
        return new Result<>();
    }

    @PostMapping("/queryRolePermissions")
    @ApiOperation(value = "角色权限查询", notes = "角色权限查询")
    public Result<List<RolePermissionDetailVO>> queryRolePermissions(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 查询角色权限关系
        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", id);
        List<SysRolePermissionDTO> rolePermissions = sysRolePermissionService.selectList(wrapper);

        if (rolePermissions == null || rolePermissions.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        List<Long> permissionIds = new ArrayList<>();
        for (SysRolePermissionDTO rolePermission : rolePermissions) {
            permissionIds.add(rolePermission.getPermissionId());
        }

        // 查询权限详情
        Wrapper<SysPermissionsDTO> permissionWrapper = new EntityWrapper<>();
        permissionWrapper.in("id", permissionIds);
        List<SysPermissionsDTO> permissions = sysPermissionsService.selectList(permissionWrapper);

        // 转换为VO
        List<RolePermissionDetailVO> voList = new ArrayList<>();
        for (SysPermissionsDTO permission : permissions) {
            RolePermissionDetailVO vo = new RolePermissionDetailVO();
            vo.setPermissionId(permission.getId());
            vo.setPermissionName(permission.getPermissionName());
            vo.setPermissionCode(permission.getPermissionCode());
            vo.setType(permission.getType());
            vo.setUrl(permission.getUrl());
            voList.add(vo);
        }

        return new Result<>(voList);
    }

}


